import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import * as _ from "lodash";
@Injectable()
export class MailDbService {
    mail:object = { "name": "邮箱" };
    constructor(
        @InjectModel('mail') private readonly MailModel,
    ) { }
    async create(createDto): Promise<any> {
        let userInfo = await this.find();
        let createdMail;
        const options = { upsert: true, new: true, setDefaultsOnInsert: true };
        if (userInfo.length) {
            createdMail = _.assign(userInfo[0].userMail, createDto.userMail);
            // console.log(createdMail);
        } else {
            createdMail = createDto.userMail;
            // console.log(createdMail);
        }
        return await this.MailModel.findOneAndUpdate(this.mail, { userMail: createdMail }, options, (err, raw) => {
            if (err) return;
            console.log('success');
        });
    }
    
    async find(){
       return await this.MailModel.find(this.mail).exec();
    }

    async deleteMail(name:string){
        const update = {"$unset":{}};
        update.$unset[`userMail.${name}`] = true;
        await this.MailModel.update(this.mail,update);
     }
}